<template>
  <div class="app-container">
    <div class="search-container">搜索区域</div>
    <el-card>
      <div class="app__body__container">
        <div class="ma__b__15">
          <el-button type="success" :icon="Plus" @click="linkToAddOrder(0)"
            >新增工单</el-button
          >
          <el-button type="danger" :icon="Delete" @click="handleDeleteAll"
            >批量删除</el-button
          >
        </div>
        <el-table
          ref="multipleTableRef"
          @selection-change="handleSelectionChange"
          :data="tableData"
          stripe
          border
          style="width: 100%"
          v-loading="loading"
          :max-height="tableHeight"
        >
          <el-table-column type="selection" width="55" fixed="left" />
          <el-table-column label="序号" fixed="left" width="100" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            :label="header.label"
            :prop="header.key"
            v-for="(header, headerIndex) in tableHeaderList"
            :key="header.fieldId"
            width="200"
            :fixed="headerIndex === 0 || headerIndex === 1 ? 'left' : false"
          >
            <template #default="scope">
              <template
                v-if="
                  header.key !== 'craft_state' && header.formType !== 'image'
                "
              >
                {{ scope.row[header.key]?.showTableValue || "" }}
              </template>
              <template v-if="header.key === 'craft_state'">
                <div>
                  当前进度： {{ scope.row[header.key]?.orderSchedule || "" }}
                </div>
                <div>
                  <el-button
                    type="primary"
                    size="small"
                    :icon="Coin"
                    @click="showCraftDialog"
                    >工艺详情</el-button
                  >
                </div>
              </template>
              <template v-if="header.formType === 'image'">
                <div v-if="scope.row[header.key]?.showTableValue.length > 1">
                  <el-button
                    type="primary"
                    size="small"
                    :icon="PictureFilled"
                    @click="
                      showImageDialog(scope.row[header.key]?.showTableValue)
                    "
                    >图片详情</el-button
                  >
                </div>
                <div v-else>
                  <el-image
                    style="width: 60px; height: 60px"
                    :src="scope.row[header.key]?.showTableValue[0]"
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-src-list="[
                      scope.row[header.key]?.showTableValue[0],
                    ]"
                    :initial-index="4"
                    fit="cover"
                  />
                </div>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            width="250"
            align="center"
          >
            <template #default="scope">
              <el-button
                type="primary"
                :icon="Edit"
                @click="handleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                :icon="Delete"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- <div class="app__body__table__pagination">
          <pagination
            v-if="count > 0"
            v-model:total="count"
            v-model:page="pageInfo.page"
            v-model:limit="pageInfo.limit"
            @pagination="handleQuery"
          />
        </div> -->
      </div>
    </el-card>
    <ImageDialog ref="imageDialogRef" />
  </div>
</template>

<script lang="ts" setup name="PageName">
defineOptions({
  name: "OrderManager",
  inheritAttrs: false,
});
import { useRouter } from "vue-router";
import {
  Plus,
  Edit,
  Delete,
  Search,
  SortDown,
  SortUp,
  PictureFilled,
  Coin,
} from "@element-plus/icons-vue";
import { type ElTable, TableColumnCtx } from "element-plus";
const router = useRouter();
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<any[]>([]);

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};
import { type OrderFieldItem } from "@/api/order/types";
import { getOrderList, getOrderField, delOrder } from "@/api/order";
const tableHeaderList = ref<OrderFieldItem[]>([]);
const tableHeaderKeys = ref<string[]>([]);
const tableData = ref<any[]>([]);
const orderStateMapNew = ["未生产", "未生产", "生产中", "已完工"]; // 工单状态列表
const loading = ref<boolean>(false);
const pageInfo = ref<PageInfoType>({
  page: 1,
  limit: 0,
});
const count = ref<number>(0);

// 获取自定义字段
const getOrderFieldService = async () => {
  let params = {
    page: 1,
    limit: 0,
  };
  let res = await getOrderField(params);
  if (res) {
    res.data.list
      .sort((a: OrderFieldItem, b: OrderFieldItem) => {
        return a.sort - b.sort;
      })
      .forEach((elm: OrderFieldItem) => {
        // console.log("自定义字段对象 ", elm.sort);
        tableHeaderList.value.push(elm);
        tableHeaderKeys.value.push(elm.key);
      });
    // 获取工单列表
    getOrderListService();
  }
};
// 获取工单列表
const getOrderListService = async () => {
  let params = {
    ...pageInfo.value,
    filter: {},
  };
  loading.value = true;
  let res = await getOrderList(params);
  console.log("获取了工单列表  ", res.data);
  if (res) {
    count.value = res.data.count;
    tableData.value = [];
    res.data.list.forEach((elm: any) => {
      // console.log("elm  ", elm);
      if (elm.extra) {
        type pushObject = {
          [key: string]: any;
        };
        let pushObj: pushObject = {};
        tableHeaderKeys.value.forEach((key: string) => {
          const findObj = elm.extra.find((extra: any) => extra.key === key);

          if (findObj) {
            // console.log(
            //   "label: ",
            //   findObj.label,
            //   "key: ",
            //   findObj.key,
            //   "value: ",
            //   findObj.value
            // );
            pushObj[key] = findObj;
            pushObj[key].showTableValue = getShowTableValue(findObj);
            if (key === "craft_state") {
              pushObj[key].orderSchedule = getOrderSchedule(findObj.value);
            }
            if (key === "117") {
              // 紧急程度
              pushObj["bgColor"] = Number(findObj.value) === 2 ? "red__bg" : "";
            }

            pushObj["company"] = elm.company;
            pushObj["companyId"] = elm.companyId;
            pushObj["orderId"] = elm.orderId;
            pushObj["status"] = elm.status;
          } else {
            pushObj[key] = {
              ...elm,
              value: "/",
              showTableValue: "/",
            };
          }
        });
        tableData.value.push(pushObj);
      }
    });
    // console.log("tableData.value  ", tableData.value);
    // tableData.value.forEach((elm) => {
    //   for (let key in elm) {
    //     console.log(
    //       "elm:::::  ",
    //       elm[key].label,
    //       "-->",
    //       elm[key].key,
    //       "-->",
    //       elm[key].showTableValue
    //     );
    //   }
    // });
  }
  loading.value = false;
};
// 计算工艺进度
const getOrderSchedule = (contentList: any[] | string) => {
  // console.log("计算进度了  ");
  if (!contentList || !contentList.length) {
    return "/";
  }
  if (contentList === "/") {
    return "/";
  }
  if (Array.isArray(contentList)) {
    let filterList = contentList.filter((elm: any) => elm.isDone == 1);
    let diff = filterList.length
      ? ((filterList.length / contentList.length) * 100).toFixed(2)
      : 0;
    return diff + "%";
  }
};

// 获取表格每行中的列显示数据
// source 是自定义字段对象
const getShowTableValue = (sourceObj: any) => {
  let targetObj = sourceObj || null;
  let targetValue: string | Array<string> = "/";
  // console.log(
  //   "label: ",
  //   targetObj.label,
  //   "key: ",
  //   targetObj.key,
  //   "value: ",
  //   targetObj.value
  // );
  if (targetObj) {
    switch (targetObj.formType) {
      case "radio":
        // eslint-disable-next-line no-case-declarations
        const targetOption = targetObj.option;
        // eslint-disable-next-line no-case-declarations
        const findValueObj =
          targetOption.find((elm: any) => elm.value == targetObj.value) || null;
        if (findValueObj) {
          targetValue = findValueObj.label;
        } else {
          targetValue = "/";
        }
        // console.log('targetObj.key ', targetObj.key)
        // console.log('targetObj.value ', targetObj.value)
        break;
      case "checkbox":
        if (Array.isArray(targetObj.value)) {
          let valueList =
            targetObj.value.map((elm: any) => {
              const findObj =
                targetObj.option.find((cElm: any) => cElm.value == elm) || null;
              if (findObj) {
                return findObj.label;
              } else {
                return "无数据";
              }
            }) || [];
          targetValue = valueList.join(",");
        } else {
          targetValue = targetObj.value ? targetObj.value : "/";
        }
        break;
      case "image":
        // 图片需要转成数组
        if (typeof targetObj.value === "string") {
          targetValue = targetObj.value
            .replace(/null|["']|\bnull\b|\bn[a-z]+\b/gi, "")
            .trim();
          if (targetValue === "") {
            targetValue = [];
          }
        } else {
          targetValue = targetObj.value.split(",");
        }
        // console.log("图片的value、--------  ", targetValue);
        break;
      default:
        targetValue = targetObj.value;
        break;
    }
    if (targetObj.key === "order_state") {
      if (
        targetObj.value !== null &&
        targetObj.value !== "" &&
        targetObj.value !== undefined
      ) {
        targetValue = orderStateMapNew[Number(targetObj.value)];
      } else {
        targetValue = targetObj.value || "/";
      }
    }
    if (typeof targetObj.value === "string") {
      targetValue = targetObj.value
        .replace(/null|["']|\bnull\b|\bn[a-z]+\b/gi, "")
        .trim();
      if (targetValue === "") {
        targetValue = "/";
      }
    }
  } else {
    targetValue = "/";
  }
  return targetValue;
};
// 调用获取自定义字段
getOrderFieldService();

// 表格操作
// 编辑
const handleEdit = (row: any) => {
  linkToAddOrder(row.orderId);
};
// 跳转新增工单页面
const linkToAddOrder = (id: string | number = "") => {
  let param: { [key: string]: any } = {
    path: "/addOrder",
    query: {},
  };
  if (id) {
    param.query.orderId = id;
  }
  router.push(param);
};
// 删除
const handleDelete = (row: any) => {
  console.log("scopeeeeeeeee  ", row);
  ElMessageBox.confirm("您确定要删除该工单吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let ids = String(row.orderId);
      delOrderService(ids);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

// 批量删除
const handleDeleteAll = () => {
  if (!multipleSelection.value.length) {
    ElMessage({
      type: "warning",
      message: "请选择要删除的工单",
    });
    return;
  }
  ElMessageBox.confirm("是否确认删除工单?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let ids = multipleSelection.value.map((item) => item.orderId).join(",");
      delOrderService(ids);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

// 删除工单
const delOrderService = async (ids: string) => {
  let params = {};
  let res = await delOrder(ids, params);
  if (res) {
    getOrderListService();
    ElMessage({
      type: "success",
      message: "删除成功",
    });
  }
};

// 分页组件事件触发
const handleQuery = () => {
  getOrderListService();
};

let tableHeight = ref<number>(0);
// 获取并设置表格高度
const setTableHeight = () => {
  nextTick().then(() => {
    let appDom = (document.querySelector(".app-main") as HTMLElement) || null;
    if (appDom) {
      tableHeight.value = appDom.offsetHeight - 200;
    }
  });
};

// const ImageDialog = defineAsyncComponent(
//   () => import("./components/ImageDialog.vue")
// );
import ImageDialog from "./components/ImageDialog.vue";
const imageDialogRef = ref<typeof ImageDialog | null>(null);

// 显示图片弹窗
const showImageDialog = (imgList: string[] = []) => {
  imageDialogRef.value?.handleOpen(imgList);
};

// 显示工艺详情弹窗
const showCraftDialog = () => {};

onMounted(() => {
  setTableHeight();
});
</script>

<style lang="scss" scoped></style>
